package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import com.leyou.item.vto.CategoryVTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 分类Service
 */
@Service
@Transactional
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;


    public List<Category> findCategoriesById(Long pid) {
        //1.构建查询条件
        /**
         * QueryWrapper: 用于封装所有查询条件
         *     QueryWrapper对象构建：
         *         1）QueryWrapper query = Wrappers.query() 无参   自定义查询方式。例如 同时分页+条件判断等
         *         2）QueryWrapper query = Wrappers.query(T) 有参  简单查询。 例如 根据用户名查询
         */
        Category category = new Category();
        category.setParentId(pid);//设置条件

        QueryWrapper wrapper = Wrappers.query(category);

        //2.执行查询
        List<Category> categories = categoryMapper.selectList(wrapper);

        //3.处理结果
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        //4.返回结果
        return categories;
    }

    public List<Category> findCategoriesByIds(List<Long> ids) {
        List<Category> categories = categoryMapper.selectBatchIds(ids);
        if (CollectionUtils.isEmpty(categories)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return categories;
    }

    /**
     * 返三级信息给前端
     *
     * @return
     */
    public List<CategoryVTO> findCategories() {
        //1.取出一级内容
        List<Category> categoryList = this.findCategoriesById(0L);
        List<CategoryVTO> categoryVTOS = BeanHelper.copyWithCollection(categoryList, CategoryVTO.class);

        //2.取出二级内容
        for (CategoryVTO categoryVTO1 : categoryVTOS) {
            List<Category> level2 = this.findCategoriesById(categoryVTO1.getId());
            List<CategoryVTO> categoryVTOS2 = BeanHelper.copyWithCollection(level2, CategoryVTO.class);
            categoryVTO1.setCategoryVTOS(categoryVTOS2);

            for (CategoryVTO categoryVTO3 : categoryVTOS2) {
                List<Category> level3 = this.findCategoriesById(categoryVTO3.getId());
                List<CategoryVTO> categoryVTOS3 = BeanHelper.copyWithCollection(level3, CategoryVTO.class);
                categoryVTO3.setCategoryVTOS(categoryVTOS3);
            }
        }

        return categoryVTOS;
    }
}
